package com.dis.main;

import com.dis.consumer.TranforMonitoringDataConsumer;
import com.dis.entity.BaseData;
import com.dis.handler.BaseExecptionHandler;
import com.dis.producer.DataProducer;
import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DisruptorMain {

    public static void main(String[] args) throws InterruptedException {

        RingBuffer<BaseData> ringBuffer = RingBuffer.create(
                ProducerType.MULTI,
                new EventFactory<BaseData>() {
                    public BaseData newInstance() {
                        return new BaseData();
                    }
                },
                1024 * 1024,
                new YieldingWaitStrategy());


        SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();

        //todo 数量确认 消费者群组 10
        WorkHandler[] consumers = new WorkHandler[10];
        for (int i = 0; i < consumers.length; i++) {
            consumers[i] = new TranforMonitoringDataConsumer("consumer"+i);
        }

        WorkerPool<BaseData> workerPool = new WorkerPool<BaseData>(
                ringBuffer,
                sequenceBarrier,
                new BaseExecptionHandler(),
                consumers);


        ringBuffer.addGatingSequences(workerPool.getWorkerSequences());

        ExecutorService executorService = Executors.newFixedThreadPool(10);//todo 极力反对无效，人微言轻

        workerPool.start(executorService);

        CountDownLatch countDownLatch = new CountDownLatch(1);

        publish(ringBuffer,countDownLatch);


        countDownLatch.countDown();

        Thread.sleep(1000);
        publish(ringBuffer,countDownLatch);
        executorService.shutdown();
    }

    public static void publish(RingBuffer<BaseData> ringBuffer,CountDownLatch latch){
        for (int i = 0; i < 2; i++) {
            DataProducer producer = new DataProducer(ringBuffer,latch);
        }
    }
}
